package top.stacktrace.gateway.service;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Component;
import top.stacktrace.account.domain.User;
import top.stacktrace.gateway.config.auth.Token;
import top.stacktrace.gateway.config.auth.TokensAuthority;
import top.stacktrace.gateway.config.auth.UserToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class LoginCacheService {

    @Cacheable(value="login",key="#token",condition = "#token != null && #token != \"\"",unless="#result == null")
    public Token getToken(String token){
        return null;
    }

    @CacheEvict(value="login",key="#userid")
    public long delUserToken(long userid){
        return userid;
    }

    @CachePut(value = "login",key="#userid",unless="#result == null")
    public UserToken saveUser(String token, long userid){
        UserToken ut = new UserToken();
        ut.setUserid(userid);
        ut.setToken(token);
        return ut;
    }

    @Caching(evict = {
            @CacheEvict(value="login",key="#token")
    })
    public String removeToken(String token){
        return token;
    }


    @Cacheable(value="login",key="#userid",unless="#result == null")
    public UserToken getUserToken(long userid){
        return null;
    }

    @CachePut(value = "login",key = "#token")
    public Token makeToken(String token, User u){
        Token t = new Token(token);
        if(Objects.isNull(u) || u.getId() < 1){
            t.setAuthenticated(false);
        }else{
            t.setAuthenticated(true);
            t.setUserid(u.getId());
            String[] roles = u.getRole().split(",");
            List<TokensAuthority> aroles = new ArrayList<TokensAuthority>();
            for(String r:roles){
                aroles.add(new TokensAuthority(r));
            }
            t.setAuthorities(aroles);
        }
        return t;
    }
}

